package com.aiapphub.BaseCode.utils;

import com.aiapphub.BaseCode.constants.AppHttpCodeEnum;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

public class TokenUtil {


    @Value("${sso.data.url.token}")
    private String tokenUrl; // 令牌获取URL

    @Value("${sso.data.username}")
    private String username; // 用户名

    @Value("${sso.data.password}")
    private String password; // 密码

    private String accessToken;
    private long tokenExpirationTime;
    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    public TokenUtil(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
        this.objectMapper = new ObjectMapper();
    }

    // 获取token的方法
    public String fetchToken() throws IOException {
        if (accessToken == null || isTokenExpired()) {
            String requestJson = String.format("{\"username\": \"%s\", \"password\": \"%s\"}", username, password);
            HttpHeaders headers = new HttpHeaders();
            headers.set(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            HttpEntity<String> requestEntity = new HttpEntity<>(requestJson, headers);

            ResponseEntity<String> response = restTemplate.exchange(tokenUrl, HttpMethod.POST, requestEntity, String.class);
            JsonNode jsonNode = objectMapper.readTree(response.getBody());

            if (jsonNode.get("code").asInt() == AppHttpCodeEnum.TOKEN_SUCCESS.getCode()) {
                accessToken = jsonNode.get("access_token").asText();
                long expireTime = jsonNode.get("expire_time").asLong();
                tokenExpirationTime = System.currentTimeMillis() + (expireTime * 1000);
                return accessToken;
            } else {
                throw new RuntimeException("获取TOKEN失败: " + jsonNode.get("msg").asText());
            }
        }
        return accessToken;
    }

    // 检查token是否过期
    private boolean isTokenExpired() {
        return System.currentTimeMillis() >= tokenExpirationTime;
    }
}
